#!/usr/bin/env python2
# coding=utf-8

from PIL import Image
import re, os

'''
a class use for image to text with 32x32 matrix
'''
class PicToText(object):
    """docstring for PicToText"""
    def __init__(self, arg):
        super(PicToText, self).__init__()
        self.w = 32
        self.h = 32
        
    def image2text(self, img):
        I = Image.open(img)
        #I = I.convert('L')
        reimg = I.resize((32, 32))
        reimg.save(img)
        (width, height) = reimg.size
        if width == self.w and height == self.h:
            print "right 32x32"
            # zhijieshengcheng
        print width, height
        table = []
        for i in range(256):
            if i > 141:
                table.append(0)
            else:
                table.append(1)
        #print table   
        out = list(reimg.point(table, '1').getdata())
        #print out, len(out)
        a = ''
        for i in range(height):
            for j in range(width):
                a += str(out[i*width+j])
            a += '\n'
        print a
    
        namestr = ''
        name = re.search(r'/?([A-Z0-9\_]+)\.(png)', img)#.group(1)
        if name:
            namestr = name.group(1)
            print namestr
            fp = open('./txt_cache/'+namestr+'.txt', 'w')
            fp.write(a)

    def expand(self):
        pass

def main():
    images = os.listdir('./picture_cache/')
    for pic in images:
        #print p
        arg = './picture_cache/'+pic
        print arg
        p = PicToText(arg)
        p.image2text(arg)

if __name__ == '__main__':
    main()    

